package com.luming.ethtran.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luming.ethtran.domain.Result;
import com.luming.ethtran.domain.SysUser;
import com.luming.ethtran.mapper.SysUserMapper;
import com.luming.ethtran.service.ISysLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author Luming
 * @Date 2024/9/2 13:56
 * @Description:
 */
@Service
public class SysLoginServiceImpl implements ISysLoginService {
    
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public Result login(SysUser user) {
        // 查询数据库中是否存在该账户
        SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>()
                .eq("user_account", user.getUserAccount()));
        
        Result result = new Result<>();
        if (sysUser == null) {
            result.setCode(500);
            result.setMsg("不存在该账户");
            return result;
        }
        if (sysUser.getPassword().equals(user.getPassword())) {
            result.setCode(200);
            result.setMsg("登录成功");
            return result;
        }
        result.setCode(501);
        result.setMsg("密码错误");
        return result;
    }
    
    @Override
    public Result register(SysUser user) {
        Result result = new Result<>();
        
        // 检查用户名是否已存在
        SysUser existingUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>()
                .eq("user_account", user.getUserAccount()));
        if (existingUser != null) {
            result.setCode(502);
            result.setMsg("用户名已存在");
            return result;
        }
        
        // 插入新用户
        user.setUserId(null); // 让数据库自动生成 ID
        user.setStatus(1); // 默认启用
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        
        int insert = sysUserMapper.insert(user);
        if (insert > 0) {
            result.setCode(200);
            result.setMsg("注册成功");
        } else {
            result.setCode(503);
            result.setMsg("注册失败");
        }
        return result;
    }
}
